package model

import (
	"gitee.com/csingo/cDB"
	"github.com/gin-gonic/gin"
	"time"
)

const (
	PackagesTypeComposer uint64 = 0
	PackagesTypeGit      uint64 = 1
)

type Packages struct {
	ID        uint64     `gorm:"column:id" json:"id"`
	IncludeId uint64     `gorm:"column:include_id" json:"include_id"`
	Name      string     `gorm:"column:name" json:"name"`
	State     uint64     `gorm:"column:state" json:"state"`
	Type      uint64     `gorm:"column:type" json:"type"`
	Url       string     `gorm:"column:url" json:"url"`
	Version   string     `gorm:"column:version" json:"version"`
	CreatedAt *time.Time `gorm:"column:created_at;<-:create" json:"created_at"`
	UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at"`
}

func (i *Packages) Connection() string {
	return "default"
}

func (i *Packages) All(ctx *gin.Context) (result []*Packages, err error) {
	result = []*Packages{}
	err = cDB.Query(i).Find(&result).Error
	return
}

func (i *Packages) Save(ctx *gin.Context, pkg *Packages) (res *Packages, err error) {
	query := cDB.Query(i)
	if pkg.ID > 0 {
		query.Where("id = ?", pkg.ID)
	}

	err = query.Save(pkg).Error
	if err != nil {
		return
	}

	res = &Packages{}
	err = cDB.Query(i).Where("id = ?", pkg.ID).First(res).Error
	return
}

func (i *Packages) FindByName(ctx *gin.Context, name string) (*Packages, error) {
	res := &Packages{}
	err := cDB.Query(i).Where("name = ?", name).First(res).Error

	return res, err
}

func (i *Packages) FindById(ctx *gin.Context, id uint64) (*Packages, error) {
	res := &Packages{}
	err := cDB.WithContextModel(ctx, i).Where("id = ?", id).First(res).Error

	return res, err
}

func (i *Packages) FindByType(ctx *gin.Context, typ uint64) ([]*Packages, error) {
	res := []*Packages{}
	err := cDB.Query(i).
		Where("type = ?", typ).
		Order("id").
		Find(&res).
		Error

	return res, err
}

func (i *Packages) FindByIncludeId(ctx *gin.Context, includeId uint64) ([]*Packages, error) {
	res := []*Packages{}
	err := cDB.Query(i).
		Where("include_id = ?", includeId).
		Order("id").
		Find(&res).
		Error

	return res, err
}

func (i *Packages) DelById(ctx *gin.Context, id uint64) error {
	err := cDB.Query(i).Delete(&Packages{ID: id}).Error
	return err
}
